/**

Copyright 2010 ThreeTags (www.threetags.com)

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of ThreeTags nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THREETAGS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

package com.threetags.link.gae.db;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.memcache.MemcacheService.SetPolicy;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class Sequence {
    
    public static long next( String sSequenceName ) throws Exception {
        return next( sSequenceName, 0 );
    }
    
    public static long next( String sSequenceName, int nShards ) 
    throws Exception {
        
        // step 1: try to get it from memcache
        
        ShardedCounter dbCounter = ShardedCounter.get( sSequenceName, nShards ); 
        dbCounter.increment(1);
        
        MemcacheService cacheCounter = 
            MemcacheServiceFactory.getMemcacheService();
        if( cacheCounter == null ) throw new RuntimeException(
                "The memcache service is unavailable.");
        
        Long res = cacheCounter.increment(sSequenceName, 1);
        if( res != null ) return res;
        
        // step 2: set memcache in a transactional way
        
        System.out.println("Sequence [" + sSequenceName + 
            "] not available in MemCache. Doing DB counter sync.");
        
        Objectify ofy = ObjectifyService.beginTransaction();
        try {
            // need to get our counter with a transaction-ing ofy
            dbCounter = ShardedCounter.get( ofy, sSequenceName );
            long nCount = dbCounter.getCount();
            dbCounter.incrementSerial(1);
            
            cacheCounter.put( sSequenceName, nCount, null, 
                    SetPolicy.ADD_ONLY_IF_NOT_PRESENT );
            
            ofy.getTxn().commit();
            
        } catch( Exception e ){
            if( ofy.getTxn().isActive() ) ofy.getTxn().rollback();
            
            // we continue from here, because the transaction could have been
            // aborted due to contention, and cacheCounter is 
            // set by a parallel request 
        }
        
        // step 3: let's try once more
        dbCounter = ShardedCounter.get( sSequenceName ); 
        dbCounter.increment(1);
        res = cacheCounter.increment(sSequenceName, 1);
        if( res != null ) return res;
        
        throw new RuntimeException(
            "The memcache service is not working.");
        
    } // next

} // class Sequence
